<template>
	<div style="width:100%;height:100%">
		<video class="video-js vjs-default-skin" ref="liveVideo">
			<!-- <source src="https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8" type="application/x-mpegURL" /> -->
			<!-- <source src="http://img.ksbbs.com/asset/Mon_1704/15868902d399b87.flv" type="video/x-flv" /> -->
		</video>
	</div>
	
</template>

<script>
import 'video.js/dist/video-js.css'
import videojs from "video.js";
import 'videojs-contrib-hls'
import "videojs-flvjs-es6"

// pollfill
if (typeof Object.assign != 'function') {
	Object.defineProperty(Object, 'assign', {
		value(target, varArgs) {
			if (target == null) {
				throw new TypeError('Cannot convert undefined or null to object')
			}
			const to = Object(target)
			for (let index = 1; index < arguments.length; index++) {
				const nextSource = arguments[index]
				if (nextSource != null) {
					for (const nextKey in nextSource) {
						if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
							to[nextKey] = nextSource[nextKey]
						}
					}
				}
			}
			return to
		},
		writable: true,
		configurable: true
	})
}
// as of videojs 6.6.0
const DEFAULT_EVENTS = [
	'loadeddata',
	'canplay',
	'canplaythrough',
	'play',
	'pause',
	'waiting',
	'playing',
	'ended',
	'error'
]
export default {
	components: {
	},
	props: {
		crossOrigin: {
			type: String,
			default: ''
		},
		playsinline: {
			type: Boolean,
			default: false
		},
		customEventName: {
			type: String,
			default: 'statechanged'
		},
		events: {
			type: Array,
			default: () => []
		},
		options: {
			type: Object,
			required: true
		},
		globalOptions: {
			type: Object,
			default: () => ({
				autoplay: true,
				controls: false,
				// preload: 'auto',
				// fluid: false,
				// muted: false,
				controlBar: {
					remainingTimeDisplay: false,
					playToggle: {},
					progressControl: {},
					fullscreenToggle: {},
					volumeMenuButton: {
					inline: false,
					vertical: true
					}
				},
				techOrder: ['html5'],
				plugins: {}
			})
		},
	},
	data() {
		return {
			player: null,
        	reseted: true,
		}
	},
	watch: {
		// options: {
		// 	deep: true,
		// 	handler(options, oldOptions) {
		// 		console.log('options change', options)
		// 		this.dispose(() => {
		// 			if (options && options.sources && options.sources.length) {
		// 				this.initialize()
		// 			}
		// 		})
		// 	}
		// },
    },
	mounted() {
      	if (!this.player) { 
        	this.initialize()
      	}
    },
    beforeDestroy() {
      	if (this.player) { 
        	this.dispose()
      	}
    },
	// mounted () {
	// 	this.getVideo()
	// },
	methods: {
		initialize() {
			if (!this.options || !this.options.sources || this.options.sources.length==0) return 
			// videojs options
			const videoOptions = Object.assign({}, this.globalOptions, this.options)
			// let videoEl = this.$el.querySelector('video')
			// ios fullscreen
			if (this.playsinline) {
				this.$refs.liveVideo.setAttribute('playsinline', this.playsinline)
				this.$refs.liveVideo.setAttribute('webkit-playsinline', this.playsinline)
				this.$refs.liveVideo.setAttribute('x5-playsinline', this.playsinline)
				this.$refs.liveVideo.setAttribute('x5-video-player-type', 'h5')
				this.$refs.liveVideo.setAttribute('x5-video-player-fullscreen', false)
			}
			// cross origin
			if (this.crossOrigin !== '') {
				this.$refs.liveVideo.crossOrigin = this.crossOrigin
				this.$refs.liveVideo.setAttribute('crossOrigin', this.crossOrigin)
			}
			// emit event
			const emitPlayerState = (event, value) => {
				if (event) {
					this.$emit(event, this.player)
				}
				if (value) {
					this.$emit(this.customEventName, { [event]: value })
				}
			}
			// avoid error "VIDEOJS: ERROR: Unable to find plugin: __ob__"
			if (videoOptions.plugins) {
				delete videoOptions.plugins.__ob__
			}
			// videoOptions
			// console.log('videoOptions', videoOptions)
			
			// player
			const self = this
			if(videoOptions.sources[0] && videoOptions.sources[0].type=='video/x-flv'){
				videoOptions.flvjs = {
					mediaDataSource: {
						isLive: true,
						cors: false,
						withCredentials: false,
					}
				}
			}

			let $video = this.$el.querySelector('video')
			this.player = videojs($video, videoOptions, function() {
				// events
				const events = DEFAULT_EVENTS.concat(self.events).concat(self.globalEvents)
				// watch events
				const onEdEvents = {}
				for (let i = 0; i < events.length; i++) {
					if (typeof events[i] === 'string' && onEdEvents[events[i]] === undefined) {
						(event => {
							onEdEvents[event] = null
							this.on(event, () => {
								emitPlayerState(event, true)
							})
						})(events[i])
					}
				}
				// watch timeupdate
				this.on('timeupdate', function() {
					emitPlayerState('timeupdate', this.currentTime())
				})
				// player readied
				self.$emit('ready', this)
			},err=>{
			})
		},
		dispose(callback) {
			if (this.player && this.player.dispose) {
				if (this.player.techName_ !== 'Flash') {
					this.player.pause && this.player.pause()
				}
				this.player.dispose()
				if (!this.$el.children.length) {
					const video = document.createElement('video')
					video.className = 'video-js'
					if (this.crossOrigin !== '') {
						video.crossOrigin = this.crossOrigin
						video.setAttribute('crossOrigin', this.crossOrigin)
					}
					this.$el.appendChild(video)
				}
				this.player = null
				this.$nextTick(() => {
					this.reseted = false
					this.$nextTick(() => {
						this.reseted = true
						this.$nextTick(() => {
							callback && callback()
						})
					})
				})
				
			}
		},
		play () {
			if(this.player){
				this.player.play()
			}
		},
		pause () {
			if(this.player){
				this.player.pause()
			}
		},
		render() {
			this.dispose(() => {
				if (this.options && this.options.sources && this.options.sources.length) {
					this.initialize()
				}
			})
		},	
	}
}
</script>
<style>
.video-js{
	width: 100%;
	height: 100%;
}
</style>
